package top.onedream.buildsmallsoftware.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;

/**
 * web跑龙套
 *
 * @author zhangkein
 * @date 2023/05/16
 */
@Slf4j
public class WebUtils extends org.springframework.web.util.WebUtils {
    public WebUtils() {
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                InetAddress inet = null;

                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException var4) {
                    var4.printStackTrace();
                }

                assert inet != null;
                ipAddress = inet.getHostAddress();
            }
        }

        if (ipAddress != null && ipAddress.length() > 15 && ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }
        log.info("根据header获取ip："+ipAddress);
        return ipAddress;
    }

    public static void responseToJson(HttpServletResponse response, HashMap<String, Object> map) throws IOException {
        response.setContentType("application/json;character=utf-8");
        response.setHeader("Cache-Control", "no-cache");
//        JSONObject jsonObject = new JSONObject(map);
        ObjectMapper jsonObject =new ObjectMapper();
        String s = jsonObject.writeValueAsString(map);
        response.getWriter().write(s);
    }


    public static String getLocalIPAddress() {
        InetAddress inet = null;

        try {
            inet = InetAddress.getLocalHost();
        } catch (UnknownHostException var2) {
            var2.printStackTrace();
        }

        return inet.getHostAddress();
    }

    public static String getWebPath(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }
}
